package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.AddressBookService;
import com.sun.corba.se.impl.oa.poa.POAPolicyMediatorImpl_NR_UDS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    /*
    分析一个用户可以有多个地址，此时user与addressbook表为一对多关系，此时我们还要为添加的地址，传入，当前用户id（userid)
     */
    @PostMapping
    public R saveAddressBook(@RequestBody AddressBook addressBook){
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success(null);
    }

    @GetMapping("list")
    public R addressManagePage(AddressBook addressBook){
        /*
        查询所添加的地址信息，并进行展示
         */
        addressBook.setUserId(BaseContext.getCurrentId());
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        if (addressBook.getUserId()!=null){
            lqw.eq(AddressBook::getUserId,addressBook.getUserId());
        }
        lqw.orderByDesc(AddressBook::getUpdateTime);
//        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
//        if (BaseContext.getCurrentId()==null){
//           throw new CustomException("当前用户没有登录");
//        }
//        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
//        lqw.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);
    }

    /*
    数据回显:
        1.根据id查询数据，并判断是否存在。
        2.若存在，则进行页面回显
        3.若不存在，则抛出异常
     */
    @GetMapping("/{id}")
    public R dataHuiXian(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook!=null){
            return R.success(addressBook);
        }else {
            return R.error("没有找到该对象");
        }

    }

    /*
    保存地址
     */
    @PutMapping
    public R update(@RequestBody AddressBook addressBook){
        /*
        1.获取传入过来的数据，进行数据库更新
         */
        addressBookService.updateById(addressBook);
        return R.success(null);
    }

    /*
    删除地址
     */
    @DeleteMapping
    public R deleteAddressBook(@RequestParam Long ids){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getId, ids);
        AddressBook addressBook = addressBookService.getOne(lqw);
        if (addressBook!=null){
            addressBookService.removeById(ids);
            return R.success(null);
        }

        return R.error("删除对象不存在!");
    }

    @PutMapping("/default")
    public R setDefaultStatus(@RequestBody AddressBook addressBook){
        /*
        设置默认地址，其实就是把当前状态由0改为1，此时只能允许有一个默认地址，于是先进行数据库状态归0.然后在进行改变
         */
//        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(AddressBook::getUserId, BaseContext.getCurrentId());
//        List<AddressBook> addressBooks = addressBookService.list(lqw);
//        List<AddressBook> collect = addressBooks.stream().map((item) -> {
//            item.setIsDefault(0);
//            return item;
//        }).collect(Collectors.toList());
//        addressBookService.updateBatchById(collect);
//
//        addressBook.setIsDefault(1);
//        addressBookService.updateById(addressBook);
//        return R.success(addressBook);
        log.info("addressBook:{}", addressBook);
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ?
        addressBookService.update(wrapper);

        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }
    @GetMapping("/default")
    public R getDefaultAddress(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lqw.eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressBookService.getOne(lqw);
        if (one!=null){
            return R.success(one);
        }else {
            return R.error("没有找到该对象");
        }
    }
}
